package com.jin.controller;

import java.time.Duration;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jin.common.Result;
import com.jin.model.dto.QrLoginRequest;
import com.jin.model.dto.QrLoginResponse;
import com.jin.model.dto.QrLoginStatusResponse;
import com.jin.model.dto.WechatLoginRequest;
import com.jin.model.dto.WechatLoginResponse;
import com.jin.service.UserService;
import com.jin.util.JwtUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")

public class AuthController {

    private final UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    public AuthController(UserService userService) {
        this.userService = userService;
    }
    
    /**
     * 微信登录
     */
    @PostMapping("/wechat/login")
    public Result<WechatLoginResponse> wechatLogin(@Validated @RequestBody WechatLoginRequest request) {
        try {
            log.info("WeChat login request received with code: {}", request.getCode());
            
            WechatLoginResponse response = userService.wechatLogin(request);
            
            log.info("WeChat login successful for user: {}", response.getUserId());
            return Result.success("登录成功", response);
            
        } catch (Exception e) {
            log.error("WeChat login failed", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 刷新令牌
     */
    @PostMapping("/refresh")
    public Result<String> refreshToken(@RequestHeader("Authorization") String refreshToken) {
        try {
            // TODO: 实现刷新令牌逻辑
            return Result.error("功能开发中");
        } catch (Exception e) {
            log.error("Token refresh failed", e);
            return Result.error("刷新令牌失败：" + e.getMessage());
        }
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout(@RequestHeader("Authorization") String token) {
        try {
            // TODO: 实现退出登录逻辑（如将token加入黑名单）
            log.info("User logout");
            return Result.success("退出成功");
        } catch (Exception e) {
            log.error("Logout failed", e);
            return Result.error("退出失败：" + e.getMessage());
        }
    }

    /**
     * 生成扫码登录二维码
     */
    @PostMapping("/qr/generate")
    public Result<QrLoginResponse> generateQrCode() {
        try {
            // 生成唯一的会话ID
            String sessionId = UUID.randomUUID().toString();

            // 在Redis中存储会话状态，5分钟过期
            String sessionKey = "qr_login:session:" + sessionId;
            redisTemplate.opsForValue().set(sessionKey, "waiting", Duration.ofMinutes(5));

            // 生成小程序页面路径（包含会话ID）
            String qrContent = "pages/auth/qr-login?sessionId=" + sessionId;

            log.info("Generated QR login session: {}", sessionId);

            QrLoginResponse response = new QrLoginResponse(sessionId, qrContent, 300L);
            return Result.success("二维码生成成功", response);

        } catch (Exception e) {
            log.error("Generate QR code failed", e);
            return Result.error("生成二维码失败：" + e.getMessage());
        }
    }

    /**
     * 检查扫码登录状态
     */
    @GetMapping("/qr/status")
    public Result<QrLoginStatusResponse> checkQrLoginStatus(@RequestParam String sessionId) {
        try {
            String sessionKey = "qr_login:session:" + sessionId;
            String status = redisTemplate.opsForValue().get(sessionKey);

            if (status == null) {
                // 会话已过期
                return Result.success("会话已过期", new QrLoginStatusResponse("expired"));
            } else if (status.equals("waiting")) {
                // 等待扫码
                return Result.success("等待扫码", new QrLoginStatusResponse("waiting"));
            } else if (status.startsWith("confirmed:")) {
                // 登录已确认，解析用户信息和token
                String userInfoJson = status.substring(10);
                // 这里简化处理，实际应该解析JSON
                String[] parts = userInfoJson.split("\\|");
                if (parts.length >= 3) {
                    String openId = parts[0];
                    String nickname = parts[1];
                    String avatarUrl = parts[2];

                    // 生成管理员JWT token（使用openId作为用户标识）
                    String adminToken = jwtUtil.generateAccessToken(0L, openId);

                    QrLoginStatusResponse.UserInfo userInfo = new QrLoginStatusResponse.UserInfo();
                    userInfo.setOpenId(openId);
                    userInfo.setNickname(nickname);
                    userInfo.setAvatarUrl(avatarUrl);

                    // 删除Redis中的会话，防止重复使用
                    redisTemplate.delete(sessionKey);

                    log.info("QR login confirmed for user: {}", openId);
                    return Result.success("登录成功", new QrLoginStatusResponse("confirmed", adminToken, userInfo));
                }
            }

            return Result.success("状态未知", new QrLoginStatusResponse("waiting"));

        } catch (Exception e) {
            log.error("Check QR login status failed", e);
            return Result.error("检查登录状态失败：" + e.getMessage());
        }
    }

    /**
     * 小程序端确认扫码登录
     */
    @PostMapping("/qr/confirm")
    public Result<String> confirmQrLogin(@Validated @RequestBody QrLoginRequest request) {
        try {
            String sessionKey = "qr_login:session:" + request.getSessionId();
            String status = redisTemplate.opsForValue().get(sessionKey);

            if (status == null) {
                return Result.error("登录会话已过期");
            }

            if (!status.equals("waiting")) {
                return Result.error("登录会话状态异常");
            }

            // 将用户信息存储到Redis中，格式：confirmed:openId|nickname|avatarUrl
            String userInfo = String.format("confirmed:%s|%s|%s",
                request.getOpenId(),
                request.getNickname(),
                request.getAvatarUrl());

            redisTemplate.opsForValue().set(sessionKey, userInfo, Duration.ofMinutes(2));

            log.info("QR login confirmed by user: {}", request.getOpenId());
            return Result.success("授权成功");

        } catch (Exception e) {
            log.error("Confirm QR login failed", e);
            return Result.error("确认登录失败：" + e.getMessage());
        }
    }
}
